﻿using System;
using System.Linq;
using System.Collections.Generic;

using Fuse8.DomainFramework.Common.Locator;
using Fuse8.DomainFramework.DataAccess;
using Fuse8.DomainFramework.DataAccess.SqlDatabase;

using Fuse8.ContentManagementFramework.Domain;
using Fuse8.ContentManagementFramework.Domain.Commands;
using Fuse8.ContentManagementFramework.DataAccess.SqlAccess.Mappers;

namespace Fuse8.ContentManagementFramework.DataAccess.SqlAccess.Commands
{
    internal class CmsPageGetApprovedRevisionsDataCommand : CmsEntityGetApprovedRevisionsCommand<CmsPage>
    {
        public override IQueryable<CmsPage> Execute()
        {
            IEnumerable<CmsPage> result = null;

            var factory = DependencyServiceLocator.Current.GetInstance<IUnitOfWorkFactory<CmsPage>>();

            var currentUnitOfWork = factory.Get(false) as SqlUnitOfWork<CmsPage>;

            if (currentUnitOfWork != null)
            {
                var mapper = DependencyServiceLocator.Current.GetInstance<ISqlEntityDataMapper<CmsPageContainer, int>>();

                var data = SqlUtility<CmsPageContainer, int>.ExecuteMultiReader(
                        currentUnitOfWork.Connection,
                        currentUnitOfWork.Transaction,
                        "cms_sp_PageGetApprovedRevisions",
                        new
                        {
                            SiteId = CommandParameter.SiteId,
                            SiteGroupId = CommandParameter.SiteGroupId,
                            PageTypeParameter = "Page" //TO DO - remove hardcoded value
                        },
                        mapper);

                if (data != null)
                {
                    result = data.Pages;
                }
            }

            return result != null ?
                result.AsQueryable() :
                new List<CmsPage>().AsQueryable();
        }
    }
}
